<template>
  <div class="alternative-container">
    <div class="bg-linear"
      id="linear">
      <div class="max-w-8xl mx-auto px-4 sm:px-6 lg:px-4 pt-5 pb-1">
        <div class="breadcrumbs space-x-2 text-base max-w-7xl mx-auto flex flex-wrap items-center tool-dom"
          :data-handle="tool.handle"
          :data-advertisement_id="tool.advertisement_id ? tool.advertisement_id : ''"
          data-page_position="AlternativesPage">
          <common-link path="/"
            class="text-gray-1000 hover:text-purple-1200 go-home">
            {{$t('home')}}
          </common-link>
          <svg-icon className="text-gray-1800 text-mini text-slate-400 mx-3"
            iconName='right_outlined'
            v-if="tool && tool.categories && tool.categories.length>0"></svg-icon>
          <common-link path="/category/:handle"
            :params="{ handle:tool.categories[0].handle }"
            class="text-gray-1000 hover:text-purple-1200 go-category"
            v-if="tool && tool.categories && tool.categories.length>0">
            {{tool.categories[0].name}}
          </common-link>
          <svg-icon className="text-gray-1800 text-mini text-slate-400 mx-3"
            iconName='right_outlined'></svg-icon>
          <common-link path="/tool/:handle"
            @click.native="handleExp(0, tool)"
            :params="{ handle: tool.handle}"
            class="text-gray-1000 hover:text-purple-1200 go-tool">
            {{tool.name}}
          </common-link>
          <svg-icon className="text-gray-1800 text-mini text-slate-400 mx-3"
            iconName='right_outlined'></svg-icon>
          <span class="text-gray-1400 text-base">
            {{$t('alternative_breadcrumbs_alternative',{toolName: tool.name})}}
          </span>
        </div>
        <div class="py-14 mt-1">
          <sponsored-by class="mb-4 text-lg text-gray-1000 font-semibold text-center"></sponsored-by>
          <h1 class="text-xl-56 text-gray-1000 break-words font-semibold text-center">{{$t('alternative_title',{toolName: tool.name, year: fullYear})}}</h1>
          <p class="text-lg text-gray-1000 text-center mt-4">
            {{$t('alternative_bannerDesc',{toolName: tool.name,toolCategory: tool && tool.categories && tool.categories.length>0 ? tool.categories[0].name : ''})}}
          </p>
        </div>
      </div>
    </div>

    <div class="bg-white"
      v-if="recommendTopList && recommendTopList.length > 0">
      <div class="max-w-8xl mx-auto px-4 sm:px-6 lg:px-4 py-5">
        <h3 class="text-26 leading-normal text-purple-1300 font-semibold break-words mb-4">{{$t('recommend_youMayLike')}}</h3>
        <div class="tools grid gap-5 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-4 mb-5">
          <min-tool v-for="(item, key) in recommendTopList"
            :key="item.handle+'-'+key"
            :isShowPic="false"
            :toolPosIndex="key"
            toolPosition="Top"
            :toolsData="item"
            :lazyLoad="false"
            :isShowTraffic="false"></min-tool>
        </div>
      </div>
    </div>

    <div class="max-w-8xl mx-auto px-4 sm:px-6 lg:px-4 pt-5 pb-16">
      <div class="bg-white p-5 sm:p-7 rounded-lg">
        <div class="bg-gray-2600 rounded-lg px-7 py-7 space-y-7">
          <div class="sub-menu">
            <a href="#overviewOf"
              class="text-lg text-gray-1000 font-semibold break-words hover:underline hover:text-purple-1300 cursor-pointer"
              @click="toBestAlternative('#overviewOf')">{{$t('alternative_part',{num: 1})}} {{$t('alternative_overviewOf',{toolName: tool.name})}}</a>
            <ul class="mt-5 space-y-5 pl-7">
              <li>
                <a href="#whatIs"
                  class="inline-block text-base text-gray-1000 break-words max-w-full hover:underline hover:text-purple-1300 cursor-pointer"
                  @click="toBestAlternative('#whatIs')">
                  {{$t('alternative_whatIs',{toolName: tool.name})}}
                </a>
              </li>
              <li>
                <a href="#coreFeatures"
                  class="inline-block text-base text-gray-1000 break-words max-w-full hover:underline hover:text-purple-1300 cursor-pointer"
                  @click="toBestAlternative('#coreFeatures')">
                  {{$t('alternative_coreFeatures',{toolName: tool.name})}}
                </a>
              </li>
              <li>
                <a href="#useCase"
                  class="inline-block text-base text-gray-1000 break-words max-w-full hover:underline hover:text-purple-1300 cursor-pointer"
                  @click="toBestAlternative('#useCases')">
                  {{$t('alternative_useCases',{toolName: tool.name})}}
                </a>
              </li>
            </ul>
          </div>
          <div class="sub-menu">
            <a href="#bestAlternative"
              class="text-lg text-gray-1000 font-semibold break-words hover:underline hover:text-purple-1300 cursor-pointer"
              @click="toBestAlternative('#bestAlternative')">
              {{$t('alternative_part',{num: 2})}} {{$t('alternative_bestAlternativeRecommendation',{toolName: tool.name})}}
            </a>
            <ul class="mt-5 space-y-5 pl-7">
              <li v-for="(tool, key) in top_alternatives"
                :key="key">
                <a :href="`#bestAlternative-${key}`"
                  class="inline-block text-base text-gray-1000 break-words max-w-full hover:underline hover:text-purple-1300 cursor-pointer"
                  @click="toBestAlternative(`#bestAlternative-${key}`)">{{key+1}}.{{tool.name}}</a>
              </li>
            </ul>
          </div>
          <div class="sub-menu">
            <a href="#freeAlternatives"
              @click="toBestAlternative('#freeAlternatives')"
              class="text-lg text-gray-1000 font-semibold break-words hover:underline hover:text-purple-1300 cursor-pointer">{{$t('alternative_part',{num: 3})}} {{$t('alternative_freeAlternatives',{toolName: tool.name})}}</a>
          </div>
          <div class="sub-menu">
            <a href="#conclusion"
              @click="toBestAlternative('#conclusion')"
              class="text-lg text-gray-1000 font-semibold break-words hover:underline hover:text-purple-1300 cursor-pointer">{{$t('alternative_part',{num: 4})}} {{$t('alternative_conclusion',{toolName: tool.name})}}</a>
          </div>
        </div>

        <div class="space-y-14 mt-9">
          <section id="overviewOf">
            <h2 class="text-32 text-gray-1000 font-semibold">
              {{$t('alternative_overviewOf',{toolName: tool.name})}}
            </h2>
            <div class="space-y-14 mt-7">
              <div class="bar"
                id="whatIs">
                <h3 class="text-2xl text-gray-1000 font-semibold">
                  {{$t('alternative_whatIs',{toolName: tool.name})}}
                </h3>
                <div class="max-w-3xl max-h-96 mx-auto flex justify-center mt-5 overflow-hidden rounded-lg">
                  <common-image class="w-full h-full"
                    :src="tool.image ? $vResetPic(tool.image, 768) : 'https://cdn.toolify.ai/default.webp'"
                    :alt="tool.name"></common-image>
                </div>
                <p class="text-base text-gray-1000 break-words mt-5"
                  v-if="hasRealVal(tool.tool_website) && hasRealVal(tool.tool_website.what_is)">
                  {{tool.tool_website.what_is}}
                  <!-- {{getLocaleText(tool.description, tool.description_locales)}} -->
                </p>
              </div>
              <div class="bar"
                id="coreFeatures"
                v-if="hasRealVal(tool.tool_website) && hasRealVal(tool.tool_website.core_features) && tool.tool_website.core_features.length > 0">
                <h3 class="text-2xl text-gray-1000 font-semibold">
                  {{$t('alternative_coreFeatures',{toolName: tool.name})}}
                </h3>
                <p class="text-base text-gray-1000 break-words mt-5 pl-5 sm:pl-14">{{$t('alternative_hasCoreFeaturesIncluding',{toolName: tool.name, num: tool.tool_website.core_features.length})}}</p>
                <div class="mt-5 bg-gray-2600 rounded-lg px-7 py-7 space-y-5 text-lg text-gray-1000 font-medium break-words">
                  <p v-for="(core, cKey) in tool.tool_website.core_features"
                    :key="cKey">{{cKey+1}}. {{core}}</p>
                </div>
                <p class="text-base text-gray-1000 break-words mt-5"
                  v-if="tool.description">
                  {{tool.description}}
                  <!-- {{getLocaleText(tool.description, tool.description_locales)}} -->
                </p>
              </div>
              <div class="bar"
                id="useCases"
                v-if="hasRealVal(tool.tool_website) && hasRealVal(tool.tool_website.use_cases) && tool.tool_website.use_cases.length > 0">
                <h3 class="text-2xl text-gray-1000 font-semibold">
                  {{$t('alternative_useCases',{toolName: tool.name})}}
                </h3>
                <p class="text-base text-gray-1000 break-words mt-5">
                  {{$t('alternative_thereAreManyUseCasesFor',{toolName: tool.name})}}
                </p>
                <div class="grid gap-4 sm:grid-cols-2 mt-5 sm:mt-7">
                  <div class="flex items-center border border-gray-2000 rounded bg-white px-4 py-4 text-base text-gray-1000 font-medium break-words"
                    v-for="(useCase, uKey) in tool.tool_website.use_cases"
                    :key="uKey">{{uKey+1}}. {{useCase}}
                  </div>
                </div>
              </div>
            </div>
          </section>
          <section id="bestAlternative">
            <h2 class="text-32 text-gray-1000 font-semibold">
              {{$t('alternative_bestAlternativeRecommendation',{toolName: tool.name})}}
            </h2>
            <top-alternatives :toolsData="top_alternatives"
              v-if="top_alternatives && top_alternatives.length>0"
              class="mt-7"></top-alternatives>

            <el-empty v-else
              class="mt-7"
              :description="$t('alternative_noMatchingTools')"></el-empty>

          </section>
          <section id="freeAlternatives">
            <h2 class="text-32 text-gray-1000 font-semibold">
              {{$t('alternative_freeAlternatives',{toolName: tool.name})}}
            </h2>
            <p class="text-base text-gray-1000 break-words mt-5"
              v-if="free_alternatives && free_alternatives.length >0"
              v-html="$t('alternative_freeAlternativesDesc',{toolName: tool.name, toolsList: getNameText(free_alternatives),num: free_alternatives.length})"></p>

            <alternative-tools :toolsData="free_alternatives"
              class="mt-7"
              v-if="free_alternatives && free_alternatives.length>0"></alternative-tools>

            <el-empty v-else
              class="mt-7"
              :description="$t('alternative_noMatchingTools')"></el-empty>
          </section>

          <section id="conclusion">
            <h2 class="text-32 text-gray-1000 font-semibold">
              {{$t('alternative_conclusion')}}
            </h2>
            <div class="space-y-5 mt-7">
              <p class="text-base text-gray-1000 break-words"
                v-html="$t('alternative_conclusionDesc01',{toolName: tool.name, toolsList: getNameText(top_alternatives)})"></p>
              <p class="text-base text-gray-1000 break-words"
                v-html="$t('alternative_conclusionDesc02',{toolName: tool.name, year:fullYear,num: free_alternatives.length})"></p>
            </div>
          </section>
        </div>
      </div>

      <div class="flex flex-wrap gap-y-5 justify-between items-center bg-white rounded-md px-5 py-4 mt-7">
        <div v-if="prev_tool && prev_tool.handle"
          class="w-full md:w-auto flex-shrink-0 flex items-center text-gray-1000 hover:text-purple-1300 group">
          <common-link path="/alternative/:handle"
            :params='{handle: prev_tool.handle }'
            class="go-alternative">
            <svg-icon className="text-xl-28 mr-3 text-gray-2500 group-hover:text-purple-1300"
              iconName='toolify_left_default'></svg-icon>
          </common-link>
          <common-link path="/alternative/:handle"
            :params='{handle: prev_tool.handle }'
            class="text-base go-alternative">{{$t('alternative_pageAlternatives',{toolName: prev_tool.name})}}</common-link>
        </div>
        <div v-else></div>
        <div v-if="next_tool && next_tool.handle"
          class="w-full md:w-auto flex-shrink-0 flex items-center text-gray-1000 hover:text-purple-1300 group justify-end">
          <common-link path="/alternative/:handle"
            :params='{handle: next_tool.handle }'
            class="text-base go-alternative">{{$t('alternative_pageAlternatives',{toolName: next_tool.name})}}</common-link>
          <common-link path="/alternative/:handle"
            :params='{handle: next_tool.handle }'
            class="go-alternative">
            <svg-icon className="text-xl-28 ml-3 text-gray-2500 group-hover:text-purple-1300"
              iconName='toolify_right_default'></svg-icon>
          </common-link>
        </div>
      </div>
    </div>

    <div class="bg-white"
      v-if="recommendBottomList && recommendBottomList.length > 0">
      <div class="max-w-8xl mx-auto px-4 sm:px-6 lg:px-4 py-5">
        <h3 class="text-26 leading-normal text-purple-1300 font-semibold break-words mb-4">{{$t('recommend_mostPeopleLike')}}</h3>
        <div class="tools grid gap-5 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-3 xl:grid-cols-4 mb-5">
          <min-tool v-for="(item, key) in recommendBottomList"
            :key="item.handle+'-'+key"
            :toolPosIndex="key"
            toolPosition="Bottom"
            :toolsData="item"></min-tool>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import mixinsExposure from '~/mixins/mixins-exposure'
import _ from 'lodash'
import { mapActions, mapState, mapMutations } from 'vuex'
export default {
  name: 'Alternative',
  head() {
    return {
      htmlAttrs: {
        lang: this.locale,
      },
      title: this.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: this.description,
        },
        {
          hid: 'og:title',
          name: 'og:title',
          content: this.title,
        },
        {
          hid: 'og:description',
          name: 'og:description',
          content: this.description,
        },
        {
          hid: 'og:url',
          name: 'og:url',
          content: this.canonicalLink,
        },
        {
          hid: 'og:image:alt',
          name: 'og:image:alt',
          content: this.title,
        },
      ],
      link: [
        {
          rel: 'canonical',
          href: this.canonicalLink,
        },
      ],
    }
  },
  async asyncData({ app, route, params, query, $axiosApi, error, store }) {
    let date = new Date()
    let fullYear = date.getFullYear()
    try {
      let [toolsRes, recommendRes] = await Promise.all([
        $axiosApi.getToolkitsAlternative({
          handle: encodeURIComponent(params.handle),
        }),
        $axiosApi.searchGetAd({
          limit: 9,
        }),
      ])

      let tool,
        comparisons,
        top_alternatives,
        free_alternatives,
        same_alternatives,
        prev_tool,
        next_tool,
        updated_at
      let description, title

      if (toolsRes.code === 200) {
        tool = toolsRes.data.tool
        comparisons = toolsRes.data.comparisons
        top_alternatives = toolsRes.data.top_alternatives
        free_alternatives = toolsRes.data.free_alternatives
        same_alternatives = toolsRes.data.same_alternatives
        prev_tool = toolsRes.data.prev_tool
        next_tool = toolsRes.data.next_tool
        updated_at = toolsRes.data.updated_at

        if (toolsRes.data.tool && toolsRes.data.tool.name) {
          title = app.i18n.t('alternative_tabTitle', {
            toolName: toolsRes.data.tool.name,
            fullYear: fullYear,
          })
          if (top_alternatives && top_alternatives.length > 0) {
            let toolListText = ''
            top_alternatives.forEach((item) => {
              toolListText = `${toolListText}${toolListText ? ', ' : ''}${
                item.name
              }`
            })
            description = app.i18n.t('alternative_tabDesc', {
              toolName: toolsRes.data.tool.name,
              toolList: toolListText,
            })
          }
        }
      } else {
        if (toolsRes && toolsRes.code && toolsRes.code === 404) {
          error({ statusCode: 404 })
        } else if (!(toolsRes && toolsRes.code && toolsRes.code === 401)) {
          error({
            message:
              'There is a problem with the network. Please refresh and try again later',
            statusCode: toolsRes.code,
          })
        }
      }

      let recommendTopList = []
      let recommendBottomList = []
      if (
        recommendRes.code === 200 &&
        recommendRes.data &&
        recommendRes.data.featured_list &&
        recommendRes.data.featured_list.length > 0
      ) {
        store.commit(
          'SET_TOP_ADVERTISER',
          JSON.parse(JSON.stringify(recommendRes.data.featured_list[0]))
        )
        recommendTopList = recommendRes.data.featured_list.slice(0, 4)
        recommendBottomList = recommendRes.data.featured_list.slice(4, 8)
      } else {
        store.commit('SET_TOP_ADVERTISER', null)
      }

      return {
        tool,
        comparisons,
        top_alternatives,
        free_alternatives,
        same_alternatives,
        prev_tool,
        next_tool,
        updated_at,
        title,
        description,
        fullYear,
        recommendTopList,
        recommendBottomList,
      }
    } catch (err) {
      console.log(err)
    }
  },
  computed: {
    ...mapState({
      locale: (state) => state.locale,
    }),
  },
  watch: {
    $route: {
      handler(route) {
        if (route.name === this.$route.name) {
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mixins: [mixinsExposure],
  data() {
    return {
      canonicalLink: `https://www.toolify.ai${this.$route.fullPath}`,
      recommendTopList: [],
      recommendBottomList: [],
      tool: {},
      comparisons: null,
      top_alternatives: null,
      free_alternatives: null,
      same_alternatives: null,
      prev_tool: null,
      next_tool: null,
      updated_at: null,
      fullYear: null,

      page: 0,
      total: 0,
      per_page: 20,
      hasNext: true,

      errorImage: require('@/static/images/default.webp'),
      loading: false,
      cLoading: false,

      description: null,
      title: null,

      sameLoading: false,
    }
  },
  filters: {
    vReset: function (val) {
      if (typeof val === 'number' && !isNaN(val)) {
        if (val <= 1000) {
          return val
        } else if (val > 1000 && val < 1000000) {
          return (val / 1000).toFixed(1) + 'K'
        } else if (val >= 1000000 && val < 1000000000) {
          return (val / 1000000).toFixed(1) + 'M'
        } else {
          return (val / 1000000000).toFixed(1) + 'B'
        }
      } else {
        return val
      }
    },
    vResetVisit: function (val) {
      if (typeof val === 'number' && !isNaN(val)) {
        if (val < 5000) {
          return '< 5K'
        } else if (val >= 5000 && val < 1000000) {
          return (val / 1000).toFixed(1) + 'K'
        } else if (val >= 1000000 && val < 1000000000) {
          return (val / 1000000).toFixed(1) + 'M'
        } else {
          return (val / 1000000000).toFixed(1) + 'B'
        }
      } else {
        return '< 5K'
      }
    },
  },
  methods: {
    ...mapActions(['exposure']),
    ...mapMutations(['SET_RetrackExposure']),
    async getList() {
      this.sameLoading = true
      try {
        let req = JSON.parse(
          JSON.stringify({
            page: this.page + 1,
            per_page: 20,
            handle: encodeURIComponent(this.$route.params.handle),
          })
        )

        const res = await this.$axiosApi.getSameAlternative(req)

        this.sameLoading = false

        if (res.code === 200) {
          if (res.data.data && res.data.data.length > 0) {
            this.same_alternatives = this.same_alternatives.concat(
              res.data.data
            )
          }

          this.total = res.data.total ? res.data.total : 0
          this.page = res.data.current_page ? res.data.current_page : 1
          this.per_page = res.data.per_page ? res.data.per_page : 20
          if (!res.data.next_page_url) {
            this.hasNext = false
          }
          this.SET_RetrackExposure(Date.now())
        } else {
          //this.$message.error(res.message)
        }
      } catch (error) {
        console.log('error')
        this.sameLoading = false
      }
    },

    fI18n(arg) {
      const hasKey = this.$i18n.t(arg)
      if (hasKey) {
        const result = this.$i18n.t(arg)
        return result
      }
      return arg
    },

    getLocaleText(val, val_locales) {
      if (
        Object.prototype.toString.call(val_locales) === '[object Object]' &&
        typeof val_locales[this.locale] != 'undefined' &&
        val_locales[this.locale] !== null &&
        val_locales[this.locale] !== ''
      ) {
        return val_locales[this.locale]
      } else {
        return val
      }
    },
    getCategory(category) {
      let cText = ''
      if (category && category.length > 0) {
        category.forEach((item) => {
          cText = `${cText}${cText !== '' ? ', ' : ''}${item.name}`
        })
      }
      return cText
    },
    getNameText(arr) {
      let arrText = ''
      if (arr && arr.length > 0) {
        arr.forEach((item) => {
          arrText = `${arrText}${arrText !== '' ? ', ' : ''}${item.name}`
        })
      }
      return arrText
    },

    toBestAlternative(val) {
      const dom = document.querySelector(val)
      if (dom) {
        const top = dom.offsetTop

        const targetScrollPosition = Math.max(top - 100, 0)

        let timer = setTimeout(() => {
          window.scrollTo({
            top: targetScrollPosition,
            behavior: 'auto',
          })

          this.$nextTick(() => {
            clearTimeout(timer)
          })
        })
      }
    },

    handleExp(key = 0, toolsData) {
      this.getThrottledClickFunction(toolsData, key)()
    },
    getThrottledClickFunction(toolsData, key) {
      let functionKey = `${toolsData.handle}-${key}`
      if (!this.throttledClickFunctions[functionKey]) {
        this.throttledClickFunctions[functionKey] = _.throttle(() => {
          let exporeData = this.getExporeData(toolsData, null, null, false, {
            page_position: 'breadcrumbs',
          })
          this.exposure({
            ...exporeData,
          })
        }, 2000) // 设置节流时间间隔
      }
      return this.throttledClickFunctions[functionKey]
    },
  },
}
</script>
<style lang='scss' scoped>
.alternative-container {
  background: #f8f9fb;
  .t-label {
    padding: 3px 10px;
  }
  .favorites-icon {
    font-size: 18px;
  }
  .popular-list {
    .p-item {
      padding: 18px 0;
    }
  }
}
</style>
